module Uart_Rx_Module
(

	CLK_50M,RST_N,UART_RX,rx_bps_flag,
	out_rx_data, rx_bps_start
);


input			CLK_50M;				
input			RST_N;			
input			UART_RX;			
input 			rx_bps_flag;		
output 			rx_bps_start;		
output	[ 7:0] 	out_rx_data;		


reg		[ 1:0]	detect_edge;			
wire	[ 1:0]	detect_edge_n;			
reg				negedge_reg;		
wire			negedge_reg_n;		
reg				rx_bps_start;		
reg				rx_bps_start_n;		
reg 	[ 3:0] 	bit_cnt;				
reg 	[ 3:0] 	bit_cnt_n;				
reg 	[ 7:0] 	shift_data;		
reg 	[ 7:0] 	shift_data_n;			
reg		[ 7:0] 	out_rx_data;		
reg		[ 7:0] 	out_rx_data_n;			


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)									
		detect_edge	<= 2'b11;			
	else
		detect_edge <= detect_edge_n;		
end

//用来检测起始位。如果遇到起始位，detect_edge_n == 2'b10;
assign detect_edge_n = {detect_edge[0], UART_RX};	

//锁存起始位检测信号
always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		negedge_reg	<= 1'b0;					
	else
		negedge_reg <= negedge_reg_n;		
end

//如果检测到了起始位，则negedge_reg == 1
assign negedge_reg_n = (detect_edge == 2'b10) ? 1'b1 : 1'b0; 


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)									
		rx_bps_start <= 1'b0;			
	else
		rx_bps_start <= rx_bps_start_n;	
end

always @ (*)
begin
	if(negedge_reg)							
		rx_bps_start_n = 1'b1;				//如果检测到了起始位，则为1
	else if(bit_cnt == 4'd9)			
		rx_bps_start_n = 1'b0;				//如果一个字符接收完成，则为0
	else
		rx_bps_start_n = rx_bps_start;	    //否则不变
end

always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)									
		bit_cnt <= 4'b0;						
	else
		bit_cnt <= bit_cnt_n;				
end


always @ (*)
begin
	if(rx_bps_flag)						
		bit_cnt_n = bit_cnt + 1'b1;		
	else if(bit_cnt == 4'd9)			
		bit_cnt_n = 1'b0;						
	else
		bit_cnt_n = bit_cnt;					
end


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)									
		shift_data <= 8'b0;				
	else
		shift_data <= shift_data_n;		
end

always @ (*)
begin
	if (rx_bps_flag)
		shift_data_n = {UART_RX,shift_data[7:1]};	//rx_bps_flag为1，则采样
	else
		shift_data_n = shift_data;			
end


always @ (posedge CLK_50M or negedge RST_N)
begin
	if(!RST_N)								
		out_rx_data <= 8'b0;					
	else
		out_rx_data <= out_rx_data_n;
end


always @ (*)
begin
	if(bit_cnt == 4'd9)	
		out_rx_data_n = shift_data;		
	else
		out_rx_data_n = out_rx_data;	
end

endmodule

